package com.loonyhom.musicplayer;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.loonyhom.musicplayer.R;
import com.loonyhom.musicplayer.Control.ActivityBase;
import com.loonyhom.musicplayer.Control.MusicPlayControl;
import com.loonyhom.musicplayer.Control.MusicPlayControl.MusicPlayListener;
import com.loonyhom.musicplayer.Control.MusicPlayControl.MusicState;
import com.loonyhom.musicplayer.Control.MusicPlayControl.PlayMode;
import com.loonyhom.musicplayer.customLayout.CVLrcView;
import com.loonyhom.musicplayer.customLayout.CVPageControlView;
import com.loonyhom.musicplayer.customLayout.CVScrollLayout;
import com.loonyhom.musicplayer.customLayout.RoundImageView;
import com.loonyhom.musicplayer.Tools.DefaultLrcParser;
import com.loonyhom.musicplayer.Tools.EnvironmentDir;
import com.loonyhom.musicplayer.Tools.FileUtilTool;
import com.loonyhom.musicplayer.Tools.HttpSearchLrc;
import com.loonyhom.musicplayer.Tools.MusicInfo;
import com.loonyhom.musicplayer.Tools.PreferencesService;

public class ACT_Main_MusicPlayer extends ActivityBase implements
		MusicPlayListener {

	private static final int SHOWTIME = 500;
	private static final String TAG = "ACT_Main_MusicPlayer";
	private long firstTime;
	private int index;
	private boolean isTouchSeekbar = false;
	private MusicState status;

	private Button btn_playpause;
	private Button btn_pre;
	private Button btn_next;
	private Button btn_playmode;
	private Button btn_playlist;
	private Button btn_downLrc;
	private TextView tv_start;
	private TextView tv_end;
	private SeekBar seekbar;

	private TextView tv_title;
	private TextView tv_artist;
	private CVScrollLayout cvScrollLay;
	private CVPageControlView cvPageLay;
	private RoundImageView iv_art;
	private RelativeLayout show_lay2;
	private CVLrcView mLrcView;

	private String totaltime;
	private int totalmin = 0;
	private int totalsec = 0;
	private int min = 0;
	private int sec = 0;

	private Timer timer = null;
	private MyTimeTask task = null;

	@Override
	public void OnCreate(Bundle savedInstanceState) {
		super.OnCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.act_music_main);
		MusicPlayControl.getInstance().init(this);
		findViews();
		setListener();
		index = MusicPlayControl.getInstance().getCurrentIndex();
		status = MusicPlayControl.getInstance().getPlayState();
		updateShowInfo();

		int tmpmode = PreferencesService.getInt("playmode");
		checkSharePreferenceMode(tmpmode);
	}

	private void checkSharePreferenceMode(int tmp) {
		PlayMode mode = null;
		int modeString = 0;
		switch (tmp) {
		case 0:
			mode = PlayMode.listmode;
			modeString = R.string.list_song;
			break;
		case 1:
			mode = PlayMode.randomode;
			modeString = R.string.random_song;
			break;
		case 2:
			mode = PlayMode.onemode;
			modeString = R.string.one_song;
			break;
		}
		MusicPlayControl.getInstance().setMode(mode);
		btn_playmode.setText(modeString);
	}

	private void findViews() {
		cvScrollLay = (CVScrollLayout) findViewById(R.id.cv_scrollayout);
		cvPageLay = (CVPageControlView) findViewById(R.id.cv_pagelayout);
		cvPageLay.bindScrollLayout(cvScrollLay);// 绑定控件
		cvScrollLay.setToScreen(0);// 默认第一页
		cvPageLay.generatePageControl(0);// 默认第一个点

		// layout 1
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_artist = (TextView) findViewById(R.id.tv_artist);
		iv_art = (RoundImageView) findViewById(R.id.iv_art);

		// layout 2
		show_lay2 = (RelativeLayout) findViewById(R.id.show_lay2);
		mLrcView = (CVLrcView) findViewById(R.id.lrcView);

		tv_start = (TextView) findViewById(R.id.tv_start_time);
		tv_end = (TextView) findViewById(R.id.tv_end_time);
		seekbar = (SeekBar) findViewById(R.id.seekbar);
		btn_pre = (Button) findViewById(R.id.btn_pre);
		btn_playpause = (Button) findViewById(R.id.btn_playorpause);
		btn_next = (Button) findViewById(R.id.btn_next);
		btn_playmode = (Button) findViewById(R.id.btn_playmode);
		btn_playlist = (Button) findViewById(R.id.btn_playlist);
		btn_downLrc = (Button) findViewById(R.id.btn_downlrc);

		btn_pre.setOnClickListener(listener);
		btn_playpause.setOnClickListener(listener);
		btn_next.setOnClickListener(listener);
		btn_playmode.setOnClickListener(listener);
		btn_playlist.setOnClickListener(listener);
		btn_downLrc.setOnClickListener(listener);
	}

	private OnClickListener listener = new OnClickListener() {

		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_playorpause:
				MusicPlayControl.getInstance().startPlayMusic();
				if (isTouchSeekbar) {
					MusicPlayControl.getInstance().seekTo(
							(min * 60 + sec) * 1000);
				}
				if (MusicPlayControl.getInstance().isMusicPlaying()) {
					btn_playpause.setText(R.string.pause_music);
					startTask();
				} else {
					btn_playpause.setText(R.string.start_music);
					exitTask();
				}
				status = MusicPlayControl.getInstance().getPlayState();
				break;
			case R.id.btn_pre:
				if (MusicPlayControl.getInstance().playPreMusic()) {
					updateShowInfo();
					if (MusicPlayControl.getInstance().isMusicPlaying()) {
						startTask();
						iv_art.resetRound();
					}
				}
				break;
			case R.id.btn_next:
				if (MusicPlayControl.getInstance().playNextMusic()) {
					updateShowInfo();
					if (MusicPlayControl.getInstance().isMusicPlaying()) {
						startTask();
						iv_art.resetRound();
					}
				}
				break;
			case R.id.btn_playmode:
				checkPlayMode();
				break;
			case R.id.btn_playlist:
				Intent intent = new Intent();
				intent.setClass(ACT_Main_MusicPlayer.this,
						ACT_Music_PlayList.class);
				startActivity(intent);
				break;
			case R.id.btn_downlrc:
				new MyThread().start();
				break;
			default:
				break;
			}
		}
	};

	private OnSeekBarChangeListener onSeekBarChangeListener = new OnSeekBarChangeListener() {

		public void onStopTrackingTouch(SeekBar seekBar) {
			int seektime = seekBar.getProgress() * 1000;
			if (MusicPlayControl.getInstance().isMusicPlaying()) {
				MusicPlayControl.getInstance().seekTo(seektime);
			}

			String strSeektime = FileUtilTool.long2timeFormat(seektime);
			String[] strtmp = strSeektime.split(":");
			min = Integer.parseInt(strtmp[0]);
			sec = Integer.parseInt(strtmp[1]);
			handler.sendEmptyMessage(0);
			isTouchSeekbar = true;
		}

		public void onStartTrackingTouch(SeekBar seekBar) {
		}

		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			if (fromUser) {
				seekBar.setProgress(progress);
				seekBar.setSecondaryProgress(progress);
			}
		}
	};

	private void setListener() {
		MusicPlayControl.getInstance().setMusicPlayListener(this);
		seekbar.setOnSeekBarChangeListener(onSeekBarChangeListener);
	}

	@Override
	protected void OnResume() {
		ArrayList<MusicInfo> list = MusicPlayControl.getInstance()
				.getMusicPlayList();
		if (list != null && list.size() > 0) {
			Log.i(TAG, "index = " + index + "||| current index = "
					+ MusicPlayControl.getInstance().getCurrentIndex());
			if (index != MusicPlayControl.getInstance().getCurrentIndex()) {
				index = MusicPlayControl.getInstance().getCurrentIndex();
				updateShowInfo();
				startTask();
			} else {
				Log.i(TAG, "status = " + status + "||| current status = "
						+ MusicPlayControl.getInstance().getPlayState());
				if (status != MusicPlayControl.getInstance().getPlayState()) {
					status = MusicPlayControl.getInstance().getPlayState();
					updateShowInfo();
					startTask();
				}
			}
		} else {
			tv_title.setText(R.string.no_song);
		}
		cvScrollLay.setToScreen(cvScrollLay.getCurScreen());
		super.OnResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, Menu.FIRST, 0, R.string.scan_song);
		menu.add(Menu.NONE, Menu.FIRST + 1, 1, R.string.exit);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case Menu.FIRST:
			if (MusicPlayControl.getInstance().scanMusicFile()) {
				Toast.makeText(
						this,
						"song count = "
								+ MusicPlayControl.getInstance()
										.getMusicPlayList().size(), SHOWTIME)
						.show();
			} else {
				Toast.makeText(this, R.string.please_insert_SD, SHOWTIME)
						.show();
			}
			break;
		case Menu.FIRST + 1:
			finish();
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	protected void OnPause() {
		index = MusicPlayControl.getInstance().getCurrentIndex();
		super.OnPause();
	}

	@Override
	protected void OnDestroy() {
		MusicPlayControl.getInstance().releaseMediaPlayer();
		exitTask();
		if (MusicPlayControl.getInstance().getMusicPlayListener() != null) {
			MusicPlayControl.getInstance().setMusicPlayListener(null);
		}
		super.OnDestroy();
	}

	@Override
	public boolean OnKeyDown(int keyCode, KeyEvent event) {
		if (KeyEvent.KEYCODE_BACK == keyCode) {
			long secondTime = Calendar.getInstance().getTimeInMillis();
			if (secondTime - firstTime > 1000) {
				firstTime = secondTime;
			} else {
				finish();
				return true;
			}
			Toast.makeText(this, R.string.exit_again, SHOWTIME).show();
		}
		return super.OnKeyDown(keyCode, event);
	}

	private void checkPlayMode() {
		PlayMode mode = MusicPlayControl.getInstance().getMode();
		Log.i(TAG, "playmode1 = " + MusicPlayControl.getInstance().getMode());
		switch (mode) {
		case listmode:
			MusicPlayControl.getInstance().setMode(PlayMode.randomode);
			PreferencesService.setValue("playmode", 1);
			btn_playmode.setText(R.string.random_song);
			break;
		case randomode:
			MusicPlayControl.getInstance().setMode(PlayMode.onemode);
			PreferencesService.setValue("playmode", 2);
			btn_playmode.setText(R.string.one_song);
			break;
		case onemode:
			MusicPlayControl.getInstance().setMode(PlayMode.listmode);
			PreferencesService.setValue("playmode", 0);
			btn_playmode.setText(R.string.list_song);
			break;
		}
		Log.i(TAG, "playmode2 = " + MusicPlayControl.getInstance().getMode());
	}

	private void updateShowInfo() {
		this.index = MusicPlayControl.getInstance().getCurrentIndex();
		this.status = MusicPlayControl.getInstance().getPlayState();
		if (!HttpSearchLrc.getInstance().isExistLrc()) {
			btn_downLrc.setEnabled(true);
			mLrcView.reset();
		} else {
			btn_downLrc.setEnabled(false);
			File file = new File(EnvironmentDir.getInstance().getLrcDirectory()
					+ "/" + MusicPlayControl.getInstance().getLrcName());
			mLrcView.setLrcRows(DefaultLrcParser.getIstance().getLrcRows(file));
		}
		if (MusicPlayControl.getInstance().getCurrentMusicObject() != null) {
			MusicInfo info = MusicPlayControl.getInstance()
					.getCurrentMusicObject();

			tv_title.setText(info.getTitle());
			tv_artist.setText("－－" + info.getArtist() + "－－");
			long songid = Long.parseLong(info.getSongid());
			long albumid = Long.parseLong(info.getAlbumid());
			iv_art.setImageBitmap(FileUtilTool.getArtwork(
					ACT_Main_MusicPlayer.this, songid, albumid, true, false));
			Drawable bd = new BitmapDrawable(FileUtilTool.getArtwork(
					ACT_Main_MusicPlayer.this, songid, albumid, true, false));
			show_lay2.setBackground(bd);

			long duration = Long.parseLong(MusicPlayControl.getInstance()
					.getCurrentMusicObject().getDuration());
			seekbar.setMax((int) duration / 1000);
			totaltime = FileUtilTool.long2timeFormat(duration);

			String[] str = totaltime.split(":");
			totalmin = Integer.parseInt(str[0]);
			totalsec = Integer.parseInt(str[1]);

			if (MusicPlayControl.getInstance().isMusicPlaying()) {
				btn_playpause.setText(R.string.pause_music);
			} else {
				btn_playpause.setText(R.string.start_music);
			}

			resetShowInfo();
		}

	}

	private void resetShowInfo() {
		min = 0;
		sec = 0;
		seekbar.setProgress(0);
		seekbar.setSecondaryProgress(0);
		tv_start.setText("00:00");
		tv_end.setText(totaltime);
		exitTask();
	}

	private void startTask() {
		exitTask();
		timer = new Timer();
		task = new MyTimeTask();
		timer.schedule(task, 0, 1000);
		iv_art.startRound();
	}

	private void exitTask() {
		if (timer != null) {
			timer.cancel();
			if (task != null) {
				task.cancel();
			}
		}
		if (handler.hasMessages(0)) {
			handler.removeMessages(0);
		}
		iv_art.pauseRound();
	}

	class MyTimeTask extends TimerTask {

		@Override
		public void run() {
			handler.sendEmptyMessage(0);
		}
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 1:
				Log.i(TAG, "complete load lrc");
				Toast.makeText(ACT_Main_MusicPlayer.this,
						R.string.down_success, SHOWTIME).show();
				btn_downLrc.setEnabled(false);
				File file = new File(EnvironmentDir.getInstance()
						.getLrcDirectory()
						+ "/"
						+ MusicPlayControl.getInstance().getLrcName());
				mLrcView.setLrcRows(DefaultLrcParser.getIstance().getLrcRows(
						file));
				break;
			case -1:
				Toast.makeText(ACT_Main_MusicPlayer.this, "未搜索到歌词", SHOWTIME)
						.show();
				break;
			case 0:
				if (min == totalmin) {
					if (sec == totalsec) {
						tv_start.setText(totaltime);
						exitTask();
					} else {
						sec++;
						if (sec < 10) {
							if (min < 10) {
								tv_start.setText("0" + min + ":0" + sec);
							} else {
								tv_start.setText(min + ":0" + sec);
							}
						} else {
							if (min < 10) {
								tv_start.setText("0" + min + ":" + sec);
							} else {
								tv_start.setText(min + ":0" + sec);
							}
						}
					}
				} else {
					if (sec == 59) {
						min++;
						sec = 0;
						if (min < 10) {
							tv_start.setText("0" + min + ":00");
						} else {
							tv_start.setText(min + ":00");
						}
					} else {
						sec++;
						if (sec < 10) {
							if (min < 10) {
								tv_start.setText("0" + min + ":0" + sec);
							} else {
								tv_start.setText(min + ":0" + sec);
							}
						} else {
							if (min < 10) {
								tv_start.setText("0" + min + ":" + sec);
							} else {
								tv_start.setText(min + ":0" + sec);
							}
						}
					}
				}

				seekbar.setSecondaryProgress(min * 60 + sec);
				seekbar.setProgress(min * 60 + sec);
				mLrcView.seekTo((min * 60 + sec) * 1000, true, false);
				break;
			default:
				break;
			}

		};
	};

	public void onCompletionMusic() {
		mLrcView.reset();
		updateShowInfo();
		startTask();
	}

	class MyThread extends Thread {
		@Override
		public void run() {
			super.run();
			int res;
			res = HttpSearchLrc.getInstance().SearchLrcByHttp(
					MusicPlayControl.getInstance().getCurrentMusicObject()
							.getTitle(),
					MusicPlayControl.getInstance().getCurrentMusicObject()
							.getArtist());
			if (res == 0) {
				handler.sendEmptyMessage(-1);
			} else {
				handler.sendEmptyMessage(1);
			}
		}
	}
}
